package org.common.utils.generatormapper.event.handler.generator;
import org.common.utils.database.access.DataAccess;
import org.common.utils.database.access.DataAccessTool;
import org.common.utils.event.annotation.EventMethod;
import org.common.utils.field.FieldInfo;
import org.common.utils.generatormapper.GeneratorMapperManager;
import org.common.utils.generatormapper.data.entity.DataEntity;
import org.common.utils.generatormapper.event.entity.GeneratorEvent;
import org.common.utils.generatormapper.event.handler.generator.service.GeneratorService;
import org.common.utils.generatormapper.window.tools.DialogTool;
import org.common.utils.tool.StringTool;

import javax.swing.*;
import java.io.File;
import java.util.List;

/**
 * 生成实体类处理器
 * @author zhouzhibing
 * @date 2025/1/7
 */
public class GeneratorEventHandler {

    @EventMethod
    public void doGenerator(GeneratorEvent event) {

        JList<String> jList = event.getTblList();
        String tableName = jList.getSelectedValue();
        if(tableName == null || tableName.isEmpty()) {
            DialogTool.showMessageDialog("GeneratorEntityWindow.dialog.generator.tableName.empty");
            return;
        }

        DataAccess dataAccess = DataAccessTool.get().getDataAccess();
        List<FieldInfo> list = dataAccess.select("show full columns from " + tableName, resultSet -> new FieldInfo(
            resultSet.getString(1),
            resultSet.getString(2),
            resultSet.getString(9)
        ));

        DataEntity dataEntity = GeneratorMapperManager.getInstance().getDataManager().getDataEntity();
        checkAndCreatePath(dataEntity);

        GeneratorService.getInstance().generator(dataEntity.getJavaDir() , dataEntity.getPackageName(), tableName, list);
        DialogTool.showMessageDialog("GeneratorEntityWindow.dialog.generator.success");
    }

    /**
     * 检查生成路径
     * @param dataEntity 数据实体
     * @return 路径是否存在
     */
    private void checkAndCreatePath(DataEntity dataEntity) {
        String javaDir = dataEntity.getJavaDir();
        String packageName = dataEntity.getPackageName();
        String packagePath = packageName.replaceAll("\\.", StringTool.SEPARATOR_ESCAPE);
        String allPath = javaDir + File.separator + packagePath;

        File generatorDirFile = new File(allPath);
        if(!generatorDirFile.exists()) {
            generatorDirFile.mkdirs();
        }
    }
}
